﻿namespace BowlingGame
{
    public class Game
    {
        private readonly int[] _rolls = new int[21];
        private int _currentRoll;

        public void Roll(int pins)
        {
            _rolls[_currentRoll++] = pins;
        }

        public int Score()
        {
            int score = 0;
            int rollIndex = 0;
            for (int currentFrame = 0; currentFrame < 10; currentFrame++)
            {
                var scoreResult = ScoreFrame(rollIndex);
                score += scoreResult.Score;
                rollIndex += scoreResult.RollCount;
            }
            return score;
        }

        private struct FrameScoreResult
        {
            public int Score;
            public int RollCount;
        }

        private FrameScoreResult ScoreFrame(int rollIndex)
        {
            var result = new FrameScoreResult();
            if (IsStrike(rollIndex))
            {
                result.RollCount = 1;
                result.Score = 10 + StrikeBonus(rollIndex);
            }
            else
            {
                result.Score = FrameSum(rollIndex);
                if (IsSpare(rollIndex))
                {
                    result.Score += SpareBonus(rollIndex);
                }
                result.RollCount = 2;
            }
            return result;
        }

        #region Snip
        private int FrameSum(int rollIndex)
        {
            return _rolls[rollIndex] + _rolls[rollIndex + 1];
        }
        private int StrikeBonus(int rollIndex)
        {
            return _rolls[rollIndex + 1] +
                   _rolls[rollIndex + 2];
        }
        private bool IsStrike(int rollIndex)
        {
            return _rolls[rollIndex] == 10;
        }
        private int SpareBonus(int rollIndex)
        {
            return _rolls[rollIndex + 2];
        }
        private bool IsSpare(int rollIndex)
        {
            return _rolls[rollIndex] + _rolls[rollIndex + 1] == 10;
        }
        #endregion

    }
}
